<?php

abstract class ViewConfig
{
	protected $_scenario = '';
	
	public function __construct($scenario)
	{
		$this->setScenario($scenario);	
	}
	
	public final function setScenario($name)
	{
		$this->_scenario = $name;
	}
	
	public final function getScenario()
	{
		return $this->_scenario;
	}
	
	public final function getViewData()
	{
		$view = $this->setView();
		//return $view[$this->getScenario()];
		return $view;
	}
	
	public function setView()
	{
		if (method_exists($this, $this->getScenario() . 'View')) {
			return call_user_func(array($this, $this->getScenario() . 'View'));
		}
		return false;
	}
	
	public function getRequestData()
	{
		static $data = array();
		if (!empty($data)) {
			return $data;
		}
		$view = $this->getViewData();
		$method = $view['form']['method'];
		if ($method == 'post') {
			$method = 'getPost';
		} elseif ($method == 'get') {
			$method = 'getQuery';
		} else {
			$method = 'getParam';
		}
		foreach ($view['fields'] as $key => $item) {
			$data[$key] = Yii::app()->request->{$method}($key);
		}
		return $data;
	}
	
	public function validate()
	{
		$data = $this->getRequestData();
		$view = $this->getViewData();
		foreach ($view['fields'] as $key => $item) {
			if (!empty($item['validate'])) {
				foreach ($item['validate'] as $name => $validate) {
					if (!is_array($validate)) {
						$v_name = $validate;
						$v_params = array($data[$key]);
					} else {
						array_unshift($validate, $data[$key]);
						$v_name = $name;
						$v_params = $validate;
					}
					if (!MValidator::run($v_name, $v_params)) {
						$this->error(MValidator::messages($v_name, $item['text']), false);
					}
				}
			}
		}
	}
	
	public function error($msg, $status)
	{
		Yii::app()->util->return_json($msg, $status);
	}
}